package com.rico.web.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.rico.web.service.TestService;
import com.rico.web.testimport.HelloImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    private HelloImport helloImport;
    @Autowired
    private TestService testService;
   
    /**
     * 订单查询接口, 使用Sentinel注解实现限流
     *
     * @param name
     * @return
     */
    @SentinelResource(value = "hello", blockHandler = "handleFlowQpsException",fallback = "queryOrderInfo2Fallback")
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name, Date fromDate) {
        String line= String.format("Hello %s! %tT%n", name,fromDate);
        System.out.println(line);
        return line;
    }

    @GetMapping("/hello/{name}")
    public String helloPath(@PathVariable(value = "name") String name) {
        String line= String.format("Hello path value %s!", name);
        System.out.println(line);
        return line;
    }

    @GetMapping("/helloImport")
    public String helloImport(){
        return helloImport.toString();
    }

    @GetMapping("/testService")
    public String testService(){
        testService.testService();
        return "ok";
    }

    @GetMapping("/api/getDaoList")
    public Map<String,Object> getResp(){
        Map<String,Object> map=new HashMap<>();
        map.put("code","400");
        map.put("message","200");
        map.put("data",new ArrayList<>());
        return map;
    }


    /**
     * 订单查询接口抛出限流或降级时的处理逻辑
     *
     * 注意: 方法参数、返回值要与原函数保持一致
     * @return
     */
    public String handleFlowQpsException(String orderId, BlockException e) {
        e.printStackTrace();
        return "handleFlowQpsException for queryOrderInfo2: " + orderId;
    }

    /**
     * 接口运行时抛出的异常提供fallback处理
     *
     * 注意: 方法参数、返回值要与原函数保持一致
     * @return
     */
    public String queryOrderInfo2Fallback(String orderId, Throwable e) {
        return "fallback queryOrderInfo2: " + orderId;
    }
}
